package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.BaseConfigBean
import com.glory.cqaospda.bean.ProcessCheckBean
import com.glory.cqaospda.viewmodel.InspectDetailsItemModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import kotlinx.android.synthetic.main.activity_inspectdetailsitem.*
import kotlinx.android.synthetic.main.activity_title.*

class InspectDetailsItemActivity : BaseActivity<InspectDetailsItemModel>() {

    private var CheckResulcodePop: PopWindowsUtils.GeneralPop? = null
    private var ReasonCodecodePop: PopWindowsUtils.GeneralPop? = null
    var inspectType = ""
    var CheckResultList: ArrayList<String> = ArrayList()
    var ReasonCodeList: ArrayList<String> = ArrayList()
    lateinit var itemList: ProcessCheckBean.ItemList
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@InspectDetailsItemActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun initData() {

    }

    override fun initView(savedInstanceState: Bundle?) {

        itemList = intent.getSerializableExtra("itemList") as ProcessCheckBean.ItemList
        inspectType = intent.getStringExtra("inspectType").toString()
        tvBaseSubmit.visibility = View.GONE
        tvTitle.text = inspectType

        tvUserName.text = Constant.UserName
        FreeApi_ActivityManager.getActivityManager().addActivity(this)

        viewModel.defaultGetBaseConfig()

        CheckResultList.add("PASS")
        CheckResultList.add("FAIL")
        lineCheckResult.setOnClickListener {
            if (CheckResulcodePop == null) {
                CheckResulcodePop =
                    PopWindowsUtils.getOneChoosePop(this, flCheckResult.width, CheckResultList,
                        ivCheckResult, object : PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(string: String, potion: Int) {
                                tvCheckResult.text = string
                                if (string.equals("PASS")) {
                                    lineReasonCode.visibility = View.GONE
                                } else {
                                    lineReasonCode.visibility = View.VISIBLE
                                }
                                tvLotID.text = itemList.mLotNo + "#" + itemList.mReelID
                            }
                        }
                    )
            }

            if (CheckResulcodePop!!.isShowing) {
                CheckResulcodePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivCheckResult)
                CheckResulcodePop?.showAsDropDown(flCheckResult, 0, 0)
            }
        }

        lineReasonCode.setOnClickListener {
            if (ReasonCodecodePop == null) {
                ReasonCodecodePop =
                    PopWindowsUtils.getOneChoosePop(this, flReasonCode.width, ReasonCodeList,
                        ivReasonCode, object : PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(string: String, potion: Int) {
                                tvReasonCode.text = string
                            }
                        }
                    )
            }

            if (ReasonCodecodePop!!.isShowing) {
                ReasonCodecodePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivReasonCode)
                ReasonCodecodePop?.showAsDropDown(flReasonCode, 0, 0)
            }
        }

        btnInspectItem.setOnClickListener {
            if (Constant.isFastClick()) {
                if (tvCheckResult.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请选择检查结果", false)
                    return@setOnClickListener
                }
                if (tvCheckResult.text.toString() == "FAIL") {
                    if (tvReasonCode.text.toString() == "") {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("请选择失败原因", false)
                        return@setOnClickListener
                    }
                }
                var reelID = etReelID.text.toString()
                if (reelID.contains("#")){
                    reelID = etReelID.text.toString().split("#")[0]
                }

                if (reelID != itemList.mLotNo) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("输入的批次号与当前信息不一致，请确认", false)
                    return@setOnClickListener
                } else {
                    checkOrder()
                }
            }
        }

        viewModel.defUI.callObserve.observe(this@InspectDetailsItemActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        ReasonCodeList.clear()
                        val baseConfigBean = it.item as BaseConfigBean
                        for (item in baseConfigBean.mItemList) {
                            ReasonCodeList.add(item.mItemValue)
                        }
                    }
                    2 -> {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("提交成功", true)
                        setResult(1, intent)
                        finish()
                    }
                }
            } else {
                Constant.okgoError = false
            }
        }

        val instance = MyApp.instance
        instance!!.handler = handler
    }

    private fun checkOrder() {
//        if (etReelID.text.toString() != tvLotID.text.toString()) {
//            intent.putExtra("type", "inspecDetailsItem")
//            intent.setClass(this, SkipDialogActivity::class.java)
//            startActivityForResult(intent, 1)
//        } else {
        val map = JsonObject()
        map.addProperty("UserName", Constant.UserName)
        map.addProperty("EquipmentName", itemList.mEquipmentName)
        map.addProperty("LotNo", itemList.mLotNo)
        map.addProperty("CheckType", inspectType)
        map.addProperty("ReelID", itemList.mReelID)
        map.addProperty("OrderID", itemList.mOrderID)
        map.addProperty("CheckResult", tvCheckResult.text.toString())
        map.addProperty(
            "ReasonCode",
            if (lineReasonCode.visibility == View.GONE) "" else tvReasonCode.text.toString()
        )
        map.addProperty("State", "1")
        map.addProperty("Comment", etComment.text.toString())
        viewModel.defaultCheckOrder(map)
//        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_inspectdetailsitem
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                1 -> {
                    val map = JsonObject()
                    map.addProperty("UserName", Constant.UserName)
                    map.addProperty("EquipmentName", itemList.mEquipmentName)
                    map.addProperty("LotNo", itemList.mLotNo)
                    map.addProperty("CheckType", inspectType)
                    map.addProperty("ReelID", itemList.mReelID)
                    map.addProperty("OrderID", itemList.mOrderID)
                    map.addProperty("CheckResult", tvCheckResult.text.toString())
                    map.addProperty(
                        "ReasonCode",
                        if (lineReasonCode.visibility == View.GONE) "" else tvReasonCode.text.toString()
                    )
                    map.addProperty("State", "1")
                    map.addProperty("Comment", etComment.text.toString())
                    viewModel.defaultCheckOrder(map)
                }
                108 -> {
                    finish()
                }
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}